package com.atguigu.day04;

import com.atguigu.utils.IntegerSource;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.Comparator;

// 对整数流进行排序输出
public class Example4 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new IntegerSource())
                .keyBy(r -> 1)
                .process(new IntegerSort())
                .print();

        env.execute();
    }

    public static class IntegerSort extends KeyedProcessFunction<Integer, Integer, String> {
        private ListState<Integer> listState;

        @Override
        public void open(Configuration parameters) throws Exception {
            super.open(parameters);
            listState = getRuntimeContext().getListState(
                    new ListStateDescriptor<Integer>(
                            "list-state",
                            Types.INT
                    )
            );
        }

        @Override
        public void processElement(Integer value, Context ctx, Collector<String> out) throws Exception {
            // 每来一条数据，就保存到列表状态变量里面
            listState.add(value);

            // 将列表状态变量中的数据放到ArrayList中排序
            ArrayList<Integer> integers = new ArrayList<>();

            // listState.get()返回列表状态变量中所有数据的迭代器
            for (Integer e : listState.get()) integers.add(e);

            integers.sort(new Comparator<Integer>() {
                @Override
                public int compare(Integer t1, Integer t2) {
                    return t1 - t2;
                }
            });

            StringBuilder result = new StringBuilder();
            result.append("排序后的结果：");
            for (int i = 0; i < integers.size() - 1; i++) {
                result.append(integers.get(i));
                result.append("->");
            }
            result.append(integers.get(integers.size() - 1));
            result.append("\n\n");
            out.collect(result.toString());
        }
    }
}
